package com.itfreer.gis.datasyn.sub;

import android.util.Log;

import com.itfreer.gis.GisDatabaseHelper;
import com.itfreer.gis.datasyn.entity.ProjectEntity;
import com.itfreer.gis.datasyn.entity.TempProjectEntity;
import com.itfreer.utils.config.ConfigManager;
import com.itfreer.utils.http.HttpUtils;
import com.j256.ormlite.dao.Dao;
import com.j256.ormlite.misc.TransactionManager;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.concurrent.Callable;

/**
 * 定义工程同步服务类
 */
public class ProjectService {

    private static final String gisDataSynSN = "gisdatasyn";

    public static final ProjectService instance = new ProjectService();
    private ProjectService() {

    }

    /**
     * 保存上传同步工程
     *
     * @param synID
     * @param synPros
     * @return
     */
    public Boolean uploadSynProject(String synID, List<ProjectEntity> synPros) {
        String url = ConfigManager.getConfig("HttpUrl").toString();
        url += "/rest/" + gisDataSynSN + "/uploadSynProject/" + synID;
        try {
            return HttpUtils.post(url, synPros, Boolean.class);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 准备好数据
     * @param synid
     * @return
     */
    public Boolean readySynData(String synid) {
        String url = ConfigManager.getConfig("HttpUrl").toString();
        url += "/rest/" + gisDataSynSN + "/readySynData/" + synid;
        try {
            return HttpUtils.post(url, null, Boolean.class);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 获取准备好的同步工程信息
     * @param synid
     * @return
     */
    public Boolean getSynProject(String synid){
        final String url = ConfigManager.getConfig("HttpUrl").toString() + "/rest/" + gisDataSynSN + "/getSynProject/" + synid;
        //创建事务管理器
        TransactionManager transactionManager = new TransactionManager(GisDatabaseHelper.getInstance().getConnectionSource());
        //一个调用的事件
        Callable<Boolean> callable  = new Callable<Boolean>() {
            //如果异常被抛出 事件管理 就知道保存数据失败要回滚
            @Override
            public Boolean call() throws Exception {
                Dao<TempProjectEntity, String> dao = GisDatabaseHelper.getInstance().getDao(TempProjectEntity.class);
                // 清空表
                dao.queryRaw("delete from project_temp");

                List<TempProjectEntity> datas = HttpUtils.postList(url, null, TempProjectEntity.class);
                if(datas!=null && datas.size()>0){
                    for(TempProjectEntity item : datas){
                        dao.create(item);
                    }
                }
                return true;
            }
        };

        Boolean result;
        try {
            //执行事件
            result =  transactionManager.callInTransaction(callable);
        } catch (SQLException e) {
            result = false;
            Log.w("YKF","事务保存异常");
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 获取准备好的同步工程信息
     * @return
     */
    public Boolean synProject(){
        //创建事务管理器
        TransactionManager transactionManager = new TransactionManager(GisDatabaseHelper.getInstance().getConnectionSource());
        //一个调用的事件
        Callable<Boolean> callable  = new Callable<Boolean>() {
            //如果异常被抛出 事件管理 就知道保存数据失败要回滚
            @Override
            public Boolean call() throws Exception {
                // 清空表
                Dao<ProjectEntity, String> projectDao = GisDatabaseHelper.getInstance().getDao(ProjectEntity.class);
                projectDao.queryRaw("delete from project");

                Dao<TempProjectEntity, String> tempDao = GisDatabaseHelper.getInstance().getDao(TempProjectEntity.class);
                List<TempProjectEntity> list = tempDao.queryForAll();
                if(list!=null){
                    for(TempProjectEntity temp : list){
                        ProjectEntity pro = new ProjectEntity();
                        pro.setCanEdit(temp.getCanEdit());
                        pro.setCanSelect(temp.getCanSelect());
                        pro.setId(temp.getId());
                        pro.setLayerName(temp.getLayerName());
                        pro.setLayerType(temp.getLayerType());
                        pro.setLayerTypeName(temp.getLayerTypeName());
                        pro.setOrder(temp.getOrder());
                        pro.setPath(temp.getPath());
                        pro.setShow(temp.getShow());
                        pro.setSource(temp.getSource());
                        pro.setSourceName(temp.getSourceName());
                        pro.setSynType(temp.getSynType());
                        pro.setSynTypeName(temp.getSynTypeName());
                        pro.setValid(temp.getValid());
                        pro.setSpatialReference(temp.getSpatialReference());
                        pro.setMaxScale(temp.getMaxScale());
                        pro.setMinScale(temp.getMinScale());
                        pro.setRenderer(temp.getRenderer());
                        pro.setLabel(temp.getLabel());
                        pro.setMetadata(temp.getMetadata());
                        pro.setLabelPara(temp.getLabelPara());
                        pro.setDefaultValue(temp.getDefaultValue());

                        projectDao.create(pro);
                    }
                }

                return true;
            }
        };

        Boolean result;
        try {
            //执行事件
            result =  transactionManager.callInTransaction(callable);
        } catch (SQLException e) {
            result = false;
            Log.w("YKF","事务保存异常");
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 获取本地内容
     * @return
     */
    public List<TempProjectEntity> getLocalProject(){
        Dao<TempProjectEntity, String> dao = null;
        List<TempProjectEntity> list = null;
        try {
            dao = GisDatabaseHelper.getInstance().getDao(TempProjectEntity.class);
            list = dao.queryForAll();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return list;
    }

    /**
     * 获取本地内容
     * @return
     */
    public List<ProjectEntity> getProject(){
        Dao<ProjectEntity, String> dao = null;
        List<ProjectEntity> list = null;
        try {
            dao = GisDatabaseHelper.getInstance().getDao(ProjectEntity.class);
            list = dao.queryForAll();
            list.sort(new Comparator<ProjectEntity>() {
                @Override
                public int compare(ProjectEntity o1, ProjectEntity o2) {
                    return o1.getOrder().compareTo(o2.getOrder());
                }
            });
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return list;
    }

    /**
     * 更新状态
     * @param id
     */
    public ProjectEntity getProjectById(String id){
        Dao<ProjectEntity, String> dao = null;
        ProjectEntity entity = null;
        try {
            dao = GisDatabaseHelper.getInstance().getDao(ProjectEntity.class);
            entity = dao.queryForId(id);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return  entity;
    }

    /**
     * 更新对象
     * @param entity
     */
    public void updateProject(ProjectEntity entity){
        Dao<ProjectEntity, String> dao = null;
        try {
            dao = GisDatabaseHelper.getInstance().getDao(ProjectEntity.class);
            dao.update(entity);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取需要上传的工程
     * @return
     */
    public List<ProjectEntity> getNeedUploadProject(){
        Dao<ProjectEntity, String> dao = null;
        List<ProjectEntity> list = null;
        List<ProjectEntity> needList = new ArrayList<>();
        try {
            dao = GisDatabaseHelper.getInstance().getDao(ProjectEntity.class);
            list = dao.queryForAll();
            if(list!=null && list.size()>0){
                for(ProjectEntity item : list){
                    if(item.getSynType()!=null && (item.getSynType().equals("00") || item.getSynType().equals("02"))){
                        needList.add(item);
                    }
                }
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return needList;
    }

    /**
     * 保存上传同步工程
     *
     * @param synID
     * @return
     */
    public Boolean synUploadData(String synID) {
        String url = ConfigManager.getConfig("HttpUrl").toString();
        url += "/rest/" + gisDataSynSN + "/synUploadData/" + synID;
        try {
            return HttpUtils.post(url, null, Boolean.class);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
}
